﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

namespace rabbit_mq_consumer
{
    internal class Program
    {
        static async Task Main()
        {
            /*
             * 大概流程
             * 1.连接: 首先建立与队列服务的连接
             * 2.通道: 再通过连接创建会话通道连接交换机
             * 3.绑定消费事件: 如何处理拿到的数据(完了要应答)
             * 4.开始消费
             */

            var factory = new ConnectionFactory
            {
                UserName = "guest",
                Password = "guest",
                HostName = "localhost"
            };

            var conn = await factory.CreateConnectionAsync();
            var channel = await conn.CreateChannelAsync();

            var consumer = new AsyncEventingBasicConsumer(channel);
            consumer.ReceivedAsync += async (ch, ea) =>
            {
                string msg = Encoding.UTF8.GetString(ea.Body.ToArray());
                Console.WriteLine("拿到的数据: " + msg);

                await channel.BasicAckAsync(ea.DeliveryTag, false);
            };

            await channel.BasicConsumeAsync("direct_queue", false, consumer);

            Console.ReadKey(); // 别让应用关闭, 要消费数据
        }
    }
}
